<template>
<div :class="noBorder ? 'no-border' : 'business-box'">
  <div class="top-msg">
  <baseBusinessMessage v-bind="$attrs" :baseBusinessMsg="baseBusinessMsg" @back="$emit('cancelFun')"></baseBusinessMessage>
  <tabs
      :tabPane='tabPaneList'
      v-model="activeName"
      :isBusiness="true"
      @tab-click="handleClick"
      :oprateArr="handleOprateArr"
      @actionClick='actionClick'
  ></tabs>
  </div>
  <component :is='activeName' :isShowRule="isShowRule"  :dynamicFormList="dynamicFormList" :oldBussinessMsg="oldBussinessMsg" :isOnlyShow="isOnlyShow" :modelId="modelId" :orderId="orderId" :form="baseBusinessMsg" :fieldList="fields" :ref='activeName' @handle-oprate="handleOprate"></component>
  <!-- 不受状态权限控制 -->
  <div class="more-btn">
    <template>
      <!-- 受状态控制 -->
      <slot v-if="baseBusinessMsg.orderStatus !== 40 && baseBusinessMsg.orderStatus !== 30" name="noShowOperateBtn"></slot>
      <slot name="showOperateBtn"></slot>
    </template>
  </div>
  <div class="more-btn" v-if="isShowDealerBtn && !hiddenBtn && activeName === 'businessDetail'">
    <template>
      <template v-if="isShowTempBtn">
        <el-button size="mini" type="danger" plain @click="handleDel" v-if="orderId">删除</el-button>
        <el-button size="mini" type="primary"  @click="handleTemporary(0)">暂存</el-button>
        <el-button size="mini" type="primary"  @click="handleTemporary(10)" v-if="orderId">提交</el-button>
      </template>
      <template v-if="!orderId">
        <el-button class="cancel" size="mini" @click="$emit('cancelFun')">取消</el-button>
        <el-button size="mini" type="primary"  @click="saveFun">提交</el-button>
      </template>
      <el-button size="mini" v-if="isShowClamin" type="danger" @click.stop="$emit('onClamin', baseBusinessMsg)">领取</el-button>
      <template v-if="!isOnlyShow && !filterBtn">
        <template v-for="item in btnList">
          <el-button size="mini" type="primary"  @click.stop="handleBtnClick(item)" v-if="baseBusinessMsg.master === createUserId && item.type !== 'contactCustomer'" :key="item.type">{{item.name}}</el-button>
        </template>
      </template>
      <template v-if="type === 'createModel' && !isShowTempBtn">
        <template v-for="item in createButtonList">
          <el-button size="mini" type="primary"  @click.stop="handleBtnClick(item)" v-if="createUserId === baseBusinessMsg.createUser && item.type !== 'contactAssignee'" :key="item.type">{{item.name}}</el-button>
        </template>
      </template>
    </template>
  </div>
   <el-dialog :title="currentBtn.name" :append-to-body="true" v-if="dialogVisible" :visible.sync="dialogVisible"
  width="480px">
  <div v-if="currentBtn.chatText">{{currentBtn.chatText}}</div>
  <el-form :model="form" :rules="currentBtn.remarkType === 0 ? rules : []" ref="formRef" v-if="currentBtn.remarkType !== 2">
    <el-form-item
    prop="remarkText"
    label="备注">
    <el-input v-model="form.remarkText" type="textarea"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
</el-dialog>
 <assign ref="assign" :currentBtn="currentBtn" :tabs="tabs" @handleAssign="handleAssign" @handleFilter="handleFilter"></assign>
 <returnComp ref="returnComp" :currentBtn="currentBtn" @handleBack="handleBack"></returnComp>
</div>
</template>
<script lang="ts">
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import { commonAction, deepClone } from '@/utils/common'
import tabs from '@/components/configCommon/configTabs.vue'
import { CommonModule } from '@/store/modules/common'
import baseBusinessMessage from './baseBusinessMessage.vue'
import businessDetail from './businessDetail.vue'
import assign from './assign.vue'
import historyOrder from './historyOrder.vue'
import history from './history.vue'
import messageBoard from './messageBoard.vue'
import service from './service.vue'
import satisfaction from './satisfaction.vue'
import returnComp from './returnComp.vue'
import sla from './SLADetail.vue'
import { isUndef } from '@/afterSales/utils/common'
import { initField, emptyField } from '@/afterSales/utils/valueConfig'
import { busConfigStore } from '@/afterSales/views/config/serviceConfig/store/busConfigStore'
interface ArrayObj {
  props: {}
}
@Component({
  name: 'addOrEditBusiness',
  components: {
    historyOrder,
    messageBoard,
    assign,
    satisfaction,
    service,
    history,
    baseBusinessMessage,
    tabs,
    businessDetail,
    returnComp,
    sla
  }
})
export default class AddOrEditQueue extends Vue {
  [x: string]: any
  @Prop() public isOnlyShow!: boolean
  @Prop() public noBorder!: boolean
  @Prop() public type!: string
  @Prop() public isShowClamin!: boolean
  @Prop(Array) public agentList!: ArrayObj[]
  @Prop({ default: true }) private checkRead
  @Prop({ default: false }) private hiddenBtn
  @Prop({ default: false }) private filterBtn
  @Prop({ default: () => ({}) }) private currentFilterOpr
  @Prop({ default: () => (true) }) public isShowRule
  public rules = {
    remarkText: [{ required: true, message: '请输入备注', trigger: 'blur' }]
  };

  private dynamicFormList = [] as any

  private currentBtn: any = {}
  private form = {
    remarkText: ''
  }

  private tabs: any = []
  private dialogVisible = false
  private oldBussinessMsg: any = {}
  private baseBusinessMsg: any = {}
  private activeName = 'businessDetail'
  private fields = [] as any
  private orderId = ''
  private modelId = ''
  private dealConfig = {
    creatorButton: [],
    dealerButton: []
  }

  private handleDel () {
    const params = { id: this.orderId, modelId: this.modelId, checkDelete: false }
    if (!this.isShowTempBtn && this.currentFilterOpr) {
      Object.assign(params, { filterConfigId: this.currentFilterOpr.filterId })
    }
    this.$confirm('确定要删除该工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonAction({
        url: this.isShowTempBtn ? '/server-work/action/workOrder/delete' : '/server-flow/action/instance/delete',
        method: 'post',
        data: params
      }).then(res => {
        if (res.success) {
          this.$message.success('删除工单成功')
          this.successReset()
        }
      })
    })
  }

  private isShowTempBtn = false

  private get createUserId () {
    const { _id } = this.$store.state.common.session.user
    return _id
  }

  private btnList = []

  private createButtonList = []

  private get isShowDealerBtn () { // 工单已完成以及终止的工单不应该展示处理按钮
    return this.baseBusinessMsg.orderStatus !== 40 && this.baseBusinessMsg.orderStatus !== 30
  }

  private handleOprateArr = []
  private tabPaneList = [{
    name: '工单详情',
    type: 'businessDetail'
  }]

  private handleClick (item) {
    this.$set(this, 'handleOprateArr', [])
  }

  private actionClick (action, data) {
    this.$refs[this.activeName][action](data)
  }

  private handleSubmitBack () {
    this.$set(this.currentBtn, 'isHiddenRemark', false);
    if (this.currentBtn.popChat) {
      (this.$refs.returnComp as any).open()
    } else {
      (this.$refs.returnComp as any).close()
      this.handleBack();
    }
  }

  private handleTemporary (orderStatus?: number) {
    const data: any = { modelId: this.modelId, orderStatus: orderStatus || 0, data: this.baseBusinessMsg }
    if (orderStatus) {
      data.tempRecordId = this.orderId
    } else {
      data.id = this.orderId
    }

    commonAction({
      url: !this.orderId || orderStatus ? '/server-flow/action/instance/create' : '/server-work/action/workOrder/temp/update',
      method: 'post',
      data
    }).then(res => {
      if (res.success) {
        this.$message.success('暂存工单成功！')
        this.successReset()
      }
    })
  }

  private saveFun () {
    const pass = (this.$refs as any).businessDetail.validateForm();
    if (pass) {
      const data: any = { modelId: this.modelId, data: this.baseBusinessMsg }
      commonAction({
        url: '/server-flow/action/instance/create',
        method: 'post',
        data
      }).then(res => {
        if (res.success) {
          this.$message.success('新建工单成功！')
          this.successReset()
        }
      })
    }
  }

  private successReset () {
    this.orderId = ''
    this.$emit('cancelFun')
    this.$emit('success')
  }

  public async update (data?: any, type?: string, buttonName?: any) {
    const params: any = { modelId: this.modelId, id: this.orderId, data: this.baseBusinessMsg }
    await commonAction({
      url: '/server-work/action/workOrder/update',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        if (type === 'assign') {
          this.handleSubmitAssign(data)
        } else if (type === 'back') {
          this.handleBackSubmit(data)
        } else if (type === 'update') {
          this.handleUpdate(data && data.remarkText)
        } else if (type === 'allUpdate') {
          this.stopTerminal(data && data.remarkText, buttonName)
        } else {
          this.handleComplete(data && data.remarkText)
        }
      }
    })
  }

  // @Prop({ default: '' }) private title!: string
  private handleOprate (list) {
    this.$set(this, 'handleOprateArr', list)
  }

  public getBusinessDataById (data?: any, isShowTempBtn?: any, type?: any) {
    const { orderId, modelId, orderStatus } = data
    this.modelId = modelId
    this.orderId = orderId || data.id
    if (this.orderId) {
      this.isShowTempBtn = isShowTempBtn
      this.getActivity({ orderId: this.orderId, modelId, orderStatus }, undefined, type)
    } else {
      this.getActivity(data, true, type)
      this.isShowTempBtn = true
    }
  }

  private async getActivity (data: any, isAdd?: any, type?: any) {
    console.log(data)
    const p = [
      commonAction({ url: `/server-flow/action/definition/current/activity?orderId=${data.orderId && data.orderStatus !== 0 ? data.orderId : ''}&modelId=${data.modelId}`, method: 'get' }),
      commonAction({ url: '/server-work/action/workOrderModel/getConfig', method: 'POST', data: { modelId: data.modelId, queryFieldType: 2, showDynamicForm: true } })
    ]
    Promise.all(p).then(([res2, res1]) => {
      this.tabPaneList = [{
        name: '工单详情',
        type: 'businessDetail'
      }]
      let fields: any = []
      const obj = {}
      if (res1.success) {
        fields = res1.data.fields || []
      }
      if (res2.success) {
        this.handleFlowConfig(res2, isAdd, type)
        // eslint-disable-next-line no-unused-expressions
        res2.data?.formConfig.map(item => {
          obj[item.fieldBusinessId] = item
        })
        fields.forEach(item => {
          if (isAdd) {
            if (isUndef(this.baseBusinessMsg[item.businessId])) {
              if (item.fieldType === 'associateUser' && data?.info?.associateUser) {
                this.$set(this.baseBusinessMsg, item.businessId, data.info.associateUser)
              } else {
                this.$set(this.baseBusinessMsg, item.businessId, initField(item))
              }
            }
          }
          if (obj[item.businessId]) {
            item.hide = type !== 'all' ? obj[item.businessId].hide : false
            item.disabled = obj[item.businessId].readonly
            item.require = type !== 'all' ? obj[item.businessId].require : false
            item.groupStatus = false
          }
        })
      }
      this.fields = fields
      const dynamicList = res1.data?.dynamicFormResVO?.list || []
      if (!isAdd) {
        const feachData = { id: this.orderId || data.id, modelId: this.modelId, checkRead: this.checkRead }
        if (this.checkRead) {
          Object.assign(feachData, { filterConfigId: this.currentFilterOpr.filterId })
        }
        this.getFetchDataById(feachData, dynamicList)
      } else {
        this.oldBussinessMsg = deepClone(this.baseBusinessMsg)
        this.dynamicFormList = dynamicList
      }
    })
  }

  // private initDynamicForm (data: any, form: any) {
  //   const filters = data?.list || []; // 判定是否配置了动态表单 如果没有配置 直接返回当前的form
  //   if (!filters.length) {
  //     return form;
  //   } else {
  //   }
  // }

  private handleFlowConfig (res2: any, isAdd?: any, type?: any) {
    this.tabPaneList = this.tabPaneList.concat(res2.data.tabConfig.filter(item => {
      return type !== 'all' ? item.enable : true
    }));
    if (!isAdd) { // 如果是新增或是已完成不展示自定义按钮
      this.btnList = res2.data?.dealConfig?.dealerButton.filter(item => {
        if (item.type === 'assign') {
          this.handleAssignRange(item.assignTo)
        }
        return item.enable
      })
      this.createButtonList = res2.data?.dealConfig?.creatorButton.filter(item => {
        return item.enable
      })
    }
    this.dealConfig = res2.data?.dealConfig || {}
  }

  private handleBtnClickData () {
    const params = {
      activityId: this.baseBusinessMsg.activityId,
      buttonName: this.currentBtn.name,
      workModelId: this.modelId,
      workModelOrderId: this.orderId,
      activityName: this.baseBusinessMsg.activityName
    }
    return (data) => {
      if (data) {
        return Object.assign({}, params, data)
      } else {
        return params
      }
    }
  }

  public handleBtnClick (data: any) {
    console.log(data)
    this.currentBtn = data
    const params = this.handleBtnClickData()
    if (data.type === 'cancel' || data.type === 'terminal') {
      if (data.popChat) {
        this.dialogVisible = true
        this.form = {
          remarkText: ''
        }
      } else {
        this.update(null, 'allUpdate')
      }
    } else if (data.type === 'complete' || data.type === 'update') {
      const pass = (this.$refs as any).businessDetail.validateForm();
      if (pass) {
        if (data.popChat) {
          this.dialogVisible = true
          this.form = {
            remarkText: ''
          }
        } else {
          if (data.type === 'update') {
            this.update(null, 'update')
          } else {
            this.update()
          }
        }
      }
    } else if (data.type === 'back') {
      (this.$refs.returnComp as any).open()
    } else if (data.type === 'assign') {
      (this.$refs.assign as any).open()
    }
  }

  public AdjustmentHandler () {
    (this.$refs.assign as any).filterOpen(this.baseBusinessMsg)
  }

  private submit () {
    if ((this.$refs as any).formRef) {
      (this.$refs as any).formRef.validate((valid) => {
        if (valid) {
          this.handleSubmit()
        } else {
          return false;
        }
      });
    } else {
      this.handleSubmit()
    }
  }

  private handleSubmit () {
    this.dialogVisible = false
    if (this.currentBtn.type === 'complete') {
      this.update({ remarkText: this.form.remarkText })
    } else if (this.currentBtn.type === 'cancel' || this.currentBtn.type === 'terminal') {
      this.update({ remarkText: this.form.remarkText }, 'allUpdate')
    } else if (this.currentBtn.type === 'update') {
      this.update({ remarkText: this.form.remarkText }, 'update')
    }
  }

  public handleUpdate (remarkText?: string, buttonName?: any) {
    const params = Object.assign({}, this.handleBtnClickData()({ remarkText }), { variables: this.baseBusinessMsg })
    // 过滤器外部调用
    if (buttonName) {
      params.buttonName = buttonName
    }
    commonAction({
      url: '/server-flow/action/task/update',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        this.$message.success('处理成功！')
        this.$emit('cancelFun')
        this.$emit('success')
      }
    })
  }

  private handleComplete (remarkText?: string) {
    const params = Object.assign({}, this.handleBtnClickData()({ remarkText }), { variables: this.baseBusinessMsg })
    commonAction({
      url: '/server-flow/action/task/complete',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        this.$message.success('处理成功！')
        this.$emit('cancelFun')
        this.$emit('success')
      }
    })
  }

  private handleSubmitAssign (data: any) {
    const { technology, user, dept } = data.assignTo
    const params = Object.assign({}, this.handleBtnClickData()({ service: data.assignTo.service, dept, user, technology, remarkText: data.remarkText, variables: this.baseBusinessMsg }))
    commonAction({
      url: '/server-flow/action/task/assign',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        this.$message.success('转派成功')
        this.successReset()
      }
    })
  }

  private handleAssign (data: any) {
    this.update(data, 'assign')
  }

  // 调整当前处理人成功
  private handleFilter (data: any) {
    if (data.userValue === '') {
      this.$message.warning('当前处理人不能为空');
      return
    }
    const params = Object.assign({}, { activityId: this.baseBusinessMsg.activityId, activityName: this.baseBusinessMsg.activityName, assignee: data.userValue, orderId: this.orderId, modelId: this.modelId })
    commonAction({
      url: '/server-flow/action/task/setAssignee',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        this.$message.success('成功！');
        (this.$refs.assign as any).close()
        this.successReset()
      }
    })
  }

  private mounted () {
    if ((this.$refs as any).businessDetail) {
      setTimeout(() => {
        (this.$refs as any).businessDetail.clearValidate()
      })
    }
  }

  private handleBackSubmit (data?: any) {
    const { id, name } = data.toActivity
    const params = Object.assign({}, this.handleBtnClickData()({ remarkText: data.remark, toActivityId: id, toActivityName: name, variables: this.baseBusinessMsg }))
    commonAction({
      url: '/server-flow/action/task/back',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        this.$message.success('回退成功')
        this.successReset()
      }
    })
  }

  private handleBack (data?: any) {
    this.update(data, 'back')
  }

  public stopTerminal (remarkText?: string, buttonName?: any) {
    const params = Object.assign({}, this.handleBtnClickData()({ remarkText }))
    // 过滤器外部调用
    if (buttonName) {
      params.buttonName = buttonName
    }
    commonAction({
      url: '/server-flow/action/instance/terminal',
      method: 'post',
      data: params
    }).then(res => {
      if (res.success) {
        if (buttonName) {
          this.successReset()
        } else {
          this.getBusinessDataById({ orderId: this.orderId, modelId: this.modelId, activityId: this.baseBusinessMsg.activityId })
        }
      }
    })
  }

  private handleAssignRange (assignTo: any) {
    const tabs1 = [
      {
        name: '成员',
        type: 'user',
        list: assignTo?.user.map(item => {
          return ((CommonModule as any).publicCache.userListObj)[item]
        }),
        listMap: (CommonModule as any).publicCache.userListObj,
        defaultProps: { id: '_id', name: 'name' }
      },
      {
        name: '技能组',
        type: 'technology',
        list: assignTo?.technology.map(item => {
          return ((CommonModule as any).publicCache.queueListObj)[item]
        }),
        listMap: (CommonModule as any).publicCache.queueListObj,
        defaultProps: { id: '_id', name: 'name' }
      },
      {
        name: '服务组',
        type: 'service',
        list: assignTo?.service.map(item => {
          return busConfigStore.serviceMap[item]
        }),
        listMap: busConfigStore.serviceMap,
        defaultProps: { id: 'id', name: 'name' }
      },
      {
        name: '部门',
        type: 'dept',
        list: assignTo?.dept.map(item => {
          return ((CommonModule as any).publicCache.departmentListObj)[item]
        }),
        listMap: (CommonModule as any).publicCache.departmentListObj,
        defaultProps: {
          children: 'children',
          label: 'name',
          name: 'name',
          id: '_id'
        }
      }
    ]
    console.log(tabs1)
    this.tabs = tabs1
  }

  private getFetchDataById (data: object, dynamicList?: any) {
    commonAction({
      url: '/server-work/action/workOrder/search',
      method: 'post',
      data
    }).then(res => {
      if (res.success) {
        const agentObj = deepClone(CommonModule.publicCache.userListObj)[res.data.master]
        this.baseBusinessMsg = res.data || {}
        this.baseBusinessMsg.masterName = agentObj ? agentObj.name : '--'
        this.fields.forEach(field => {
          if (this.baseBusinessMsg[field.businessId] === undefined) {
            // 编辑
            this.$set(this.baseBusinessMsg, field.businessId, emptyField(field))
          }
        })
        this.oldBussinessMsg = deepClone(this.baseBusinessMsg)
        this.dynamicFormList = dynamicList
      }
    })
  }

  private getConfig (modelId: string) {
    commonAction({ url: '/server-work/action/workOrderModel/getConfig', method: 'post', data: { modelId, queryFieldType: 2 } }).then(res => {
      if (res.success) {
        this.fields = res.data.fields || []
      }
    })
  }
}
</script>
<style lang="stylus" scoped>
.top-msg {
  padding-top: 16px
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 10;
  padding-bottom: 0px;
  background-color: #fff;
}
.business-box {
  border: 1px solid #ecf0f3;
  border-radius: 10px;
  padding: 0px 16px 16px 16px;
  height: calc(100vh - 86px);
  overflow: auto;
  box-shadow: 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
  padding-bottom 16px
}
.business-top {
  width: 100%;
  height: 80px;
  background: #E5F3FD;
  border-radius: 4px;
  padding: 20px 24px;
  margin-bottom: 24px
  display: flex;
  justify-content: space-between;
  .title {
    font-weight 600
    color: #303753
    margin-bottom: 12px
    font-size: 14px
  }
  .sub-title {
    font-weight: 400;
    color: #767E91;
  }
  .status {
    font-weight: 400;
    color: #008BEE;
    width: 100px;
    text-align: right;
  }
  .V7_iconV7tubiao_mianfanhui {
    width: 14px
    color: #b3b9c7;
    margin-right: 12px;
    font-size: 14px;
  }
}
.no-border {
  padding: 0px 16px 16px 16px;
  height: calc(100vh - 36px);
  overflow: auto;
}
.more-btn {
  position: absolute;
  bottom: 10px;
  right: 5px;
  z-index: 10;
}
</style>
